package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.DailyReportService;
import com.google.project.client.Service.DailyReportServiceAsync;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.ProjectStaffService;
import com.google.project.client.Service.ProjectStaffServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectStaffDTO;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;

public class PMDailyReportList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<DailyReportDTO> ctbDailyReport = new CellTable<DailyReportDTO>();
	@UiField
	SimplePager pager;
	@UiField
	ListBox cbOperator;
	@UiField
	ListBox cbProject;
	@UiField
	Button btnSearch;
	@UiField
	ListBox cbStatus;

	interface Binder extends UiBinder<Widget, PMDailyReportList> {
	}

	private final ProjectServiceAsync projService = GWT
			.create(ProjectService.class);
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final DailyReportServiceAsync dailyReportService = GWT
			.create(DailyReportService.class);
	private final ProjectStaffServiceAsync staffService = GWT
			.create(ProjectStaffService.class);
	private List<DailyReportDTO> listReportDTO = new ArrayList<DailyReportDTO>();

	public String userID = "";

	public PMDailyReportList() {
		initWidget(binder.createAndBindUi(this));
		fillCbStatus();
		initTable();
		getUserID();
		getAllDailyReport();
	}

	/***
	 * Fix data to cbStatus
	 */
	public void fillCbStatus() {
		cbStatus.addItem("---Tất cả---", "-1");
		cbStatus.addItem("Chưa đọc", "1");
		cbStatus.addItem("Đã đọc", "0");
		cbStatus.addItem("Đã hủy", "3");
		cbStatus.setSelectedIndex(1);
	}

	/***
	 * Fill data to cbProject
	 */
	public void fillCbProject(final String _userId) {
		try {
			projService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

				@Override
				public void onFailure(Throwable caught) {

				}

				@Override
				public void onSuccess(List<ProjectDTO> result) {
					cbProject.addItem("---Tất cả---", "-1");
					if (result != null && result.size() > 0) {

						for (ProjectDTO proj : result) {
							if (proj.getUserId().equals(_userId)) {
								cbProject.addItem(proj.getProjectName(), proj
										.getProjectID());
							}

						}
						fillCbOperator();

					}

				}
			});
		} catch (Exception ex) {
			ex.getMessage();
		}

	}

	// fill cbOperator
	public void fillCbOperator() {
		try {
			cbOperator.addItem("---Tất cả---", "-1");
			String _projectId = cbProject
					.getValue(cbProject.getSelectedIndex());
			if (!_projectId.equalsIgnoreCase("-1")) {
				staffService.getProjectStaffList(_projectId,
						new AsyncCallback<List<ProjectStaffDTO>>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onSuccess(List<ProjectStaffDTO> result) {
								// lay tat ca opt co position=3

								if (result != null) {
									for (ProjectStaffDTO projectStaffDTO : result) {
										if (projectStaffDTO.getPosition() == 3) {
											cbOperator
													.addItem(
															projectStaffDTO
																	.getUserName(),
															projectStaffDTO
																	.getUserId());
										}
									}
								} else if (result == null) {
									listReportDTO.clear();
								}
							}
						});
			}

		} catch (Exception ex) {
			ex.getMessage();
		}
	}

	// get userID from session + load data khi moi vao
	public void getUserID() {
		loginService.getUserID(new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(String result) {

				userID = result;
				getReportByPMID(userID);
				// fill project co status=1-du an dang tien hanh
				fillCbProject(userID);
			}

		});
	}

	// getAll dailyReport where PMId + statusOfReport=1-chưa đọc
	public void getReportByPMID(String _userID) {
		int status = 1;
		dailyReportService.getDailyReportByPM(_userID, status,
				new AsyncCallback<List<DailyReportDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("getDailyReportByPM fail!");
					}

					@Override
					public void onSuccess(List<DailyReportDTO> result) {
						LoadData(result);
					}
				});
	}

	// get all DailyReport
	public void getAllDailyReport() {
		dailyReportService
				.getAllDailyReport(new AsyncCallback<List<DailyReportDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<DailyReportDTO> result) {
						if (result != null && result.size() > 0) {
							for (DailyReportDTO dailyReportDTO : result) {
								listReportDTO.add(dailyReportDTO);

							}
						}
					}
				});
	}

	// init ctbDailyReport
	public void initTable() {
		TextColumn<DailyReportDTO> index = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO object) {
				return object.getIndex()+"";
			}
		};
		
		Column<DailyReportDTO, String> projectColumn = new Column<DailyReportDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(DailyReportDTO object) {
				return object.getProjectDTO().getProjectName();
			}
		};
		projectColumn
		.setFieldUpdater(new FieldUpdater<DailyReportDTO, String>() {

			@Override
			public void update(int index,
					DailyReportDTO dailyReportDTO, String value) {
				if (Integer.parseInt((cbStatus.getValue(cbStatus
						.getSelectedIndex()))) == 1) {
					int status = 0;
					dailyReportService.updateStatusDailyReport(
							dailyReportDTO.getId(), status,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Window.alert("Có lỗi xảy ra!");

								}

								@Override
								public void onSuccess(Void result) {
									// Window.alert("ok");

								}
							});
				}
				PMEntrypoint.get().PMDailyReportDetail(dailyReportDTO);
			}
		});
		// Tên Người gửi
		TextColumn<DailyReportDTO> userReport = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO object) {
				return object.getFromUserName();
			}
		};
		// Báo cáo ngày
		TextColumn<DailyReportDTO> reportDateColumn = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO object) {
				return CommonFuntion.convertToDate(new Date(object
						.getReportForDate()));
			}
		};
		
		// ngày gửi

		TextColumn<DailyReportDTO> createdOnDate = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO object) {
				return CommonFuntion.convertToDate(new Date(object
						.getCreatedOnDate()));
			}
		};
		TextColumn<DailyReportDTO> status = new TextColumn<DailyReportDTO>() {
			@Override
			public String getValue(DailyReportDTO report) {
				String result="";
				if(report.getStatus()==1){
					result+="Chưa đọc";
				}else if(report.getStatus()==0 || report.getStatus()==2  ){
					result+="Đã đọc";
				}else if(report.getStatus()==3){
					result+="Đã hủy";
				}
				return result ;
			}
		};
		projectColumn.setCellStyleNames("celltable");
		ctbDailyReport.addColumn(index, "STT");
		ctbDailyReport.addColumn(projectColumn, "Dự án");
		ctbDailyReport.addColumn(reportDateColumn, "Báo cáo ngày");
		ctbDailyReport.addColumn(userReport, "Người báo cáo");
		ctbDailyReport.addColumn(createdOnDate, "Ngày gửi");
		ctbDailyReport.addColumn(status, "Tình Trạng");
		ctbDailyReport.setStyleName("ttable");

	}

	// load data to celltable
	protected void LoadData(List<DailyReportDTO> dailyReportList) {

		ListDataProvider<DailyReportDTO> dataProvider = new ListDataProvider<DailyReportDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbDailyReport);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index=1;
		List<DailyReportDTO> list = dataProvider.getList();
		for (DailyReportDTO dailyDetail : dailyReportList) {
			dailyDetail.setIndex(index);
			list.add(dailyDetail);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbDailyReport);
		pager.setPage(5);
	}

	// Hàm search
	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {

		Boolean condition = true;
		List<DailyReportDTO> Templist = new ArrayList<DailyReportDTO>();
		if (listReportDTO.size() > 0) {
			for (DailyReportDTO dailyReportDTO : listReportDTO) {
				if (!cbProject.getValue(cbProject.getSelectedIndex()).equals(
						"-1")) {
					String projectID = cbProject.getValue(cbProject
							.getSelectedIndex());
					condition = condition
							&& (dailyReportDTO.getProjectID().equals(projectID));

				}
				if (!cbOperator.getValue(cbOperator.getSelectedIndex()).equals(
						"-1")) {
					String operatorID = cbOperator.getValue(cbOperator
							.getSelectedIndex());
					condition = condition
							&& (dailyReportDTO.getFromUserID()
									.equals(operatorID));

				}
				if (!cbStatus.getValue(cbStatus.getSelectedIndex())
						.equals("-1")) {
					int status = Integer.parseInt(cbStatus.getValue(cbStatus
							.getSelectedIndex()));
					if (status == 0) {
						condition = condition
								&& ((dailyReportDTO.getStatus() == 0) || (dailyReportDTO
										.getStatus() == 2));
					} else if (status == 1) {
						condition = condition
								&& ((dailyReportDTO.getStatus() == 1));
					} else if (status == 3) {
						condition = condition
						&& ((dailyReportDTO.getStatus() == 3));
			}

				}
				if (condition) {
					Templist.add(dailyReportDTO);
				}
				condition = true;
			}
		}
		LoadData(Templist);
	}

	// onchange cbProject
	@UiHandler("cbProject")
	void onCbProjectChange(ChangeEvent event) {
		if (cbProject.getValue(cbProject.getSelectedIndex()) != null) {
			// cbOperator.removeFromParent();
			cbOperator.clear();
			fillCbOperator();

		}

	}
}
